package com.itany.cloud.controller;

import com.itany.cloud.entity.User;
import com.itany.cloud.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    public static final String GLOBAL_URL = "http://127.0.0.1:8001/users";

    @GetMapping
    public ResponseResult findAll(){
        // 调用服务提供者的接口
        // 获取到提供者接口的返回数据
        return restTemplate.getForObject(GLOBAL_URL,ResponseResult.class);
    }

    @GetMapping("/{id}")
    public ResponseResult findById(@PathVariable Integer id){
        // 在调用时,遇到REST风格的请求地址时,大括号中理论上可以随便写
        // 在开发中,一般仍然是按照编码规范写
        return restTemplate.getForObject(GLOBAL_URL+"/{id}",ResponseResult.class,id);
    }

    @PostMapping
    public ResponseResult addUser(User user){
        MultiValueMap params = new LinkedMultiValueMap();
        params.add("username",user.getUsername());
        params.add("password",user.getPassword());
        params.add("phone",user.getPhone());
        params.add("address",user.getAddress());
        return restTemplate.postForObject(GLOBAL_URL,params,ResponseResult.class);
    }

    @PutMapping
    public ResponseResult modifyUser(User user){
        String url = new StringBuffer()
                .append(GLOBAL_URL)
                .append("?id={id}")
                .append("&username={username}")
                .append("&password={password}")
                .append("&phone={phone}")
                .append("&address={address}")
                .toString();
        ResponseEntity<ResponseResult> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, null, ResponseResult.class, user.getId(), user.getUsername(), user.getPassword(), user.getPhone(), user.getAddress());
        return responseEntity.getBody();
    }

    @DeleteMapping("/{id}")
    public ResponseResult deleteUser(@PathVariable Integer id){
        ResponseEntity<ResponseResult> responseEntity = restTemplate.exchange(GLOBAL_URL + "/{id}", HttpMethod.DELETE, null, ResponseResult.class, id);
        return responseEntity.getBody();
    }

}
